﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WJP.Dependency;
using WJP.Events.Bus.Handlers;

namespace WJP.Events.Bus.Factories
{
    /// <summary>
    /// 这个<see cref="IEventHandlerFactory"/>使用IOC实现事件处理器的获取/释放
    /// </summary>
    public class IocHandlerFactory : IEventHandlerFactory
    {
        /// <summary>
        /// 事件处理器类型
        /// </summary>
        public Type HandlerType { get; }

        private readonly IIocResolver _iocResolver;

        /// <summary>
        /// 新建一个<see cref="IocHandlerFactory"/>实例
        /// </summary>
        /// <param name="iocResolver"></param>
        /// <param name="handlerType">事件处理器类型</param>
        public IocHandlerFactory(IIocResolver iocResolver, Type handlerType)
        {
            _iocResolver = iocResolver;
            HandlerType = handlerType;
        }

        /// <summary>
        /// 获取一个事件处理器
        /// </summary>
        /// <returns>一个事件处理器</returns>
        public IEventHandler GetHandler()
        {
            return (IEventHandler)_iocResolver.Resolve(HandlerType);
        }

        /// <summary>
        /// 获取事件处理器的类型（不创建实例）。
        /// </summary>
        /// <returns></returns>
        public Type GetHandlerType()
        {
            return HandlerType;
        }

        /// <summary>
        /// 释放一个事件处理器
        /// </summary>
        /// <param name="handler">要释放的事件处理器</param>
        public void ReleaseHandler(IEventHandler handler)
        {
            _iocResolver.Release(handler);
        }
    }
}
